package tests.update;

import static org.junit.Assert.fail;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;
import model.Subline;
import model.Transaction;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.TransactionInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

/*
 * 
 * Attempts to change the name of an existing transation
 * 
 */

public class TransactionUpdateNameTest00
{
	Budget budget;
	Line line;
	Subline subline;
	Transaction transaction;
	BudgetFactory factory;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Before
	public void setUp() throws Exception
	{
		System.out.println("Begining test: " +this.getClass());
		System.out.println("Setup");
		
		factory = new BudgetFactory();
		
		//Create a budget
        budget = (Budget) factory.create();
        budget.setName("Test budget");
        
        budget.setDescription("This is a update test budget.");
        
        line = (Line) budget.createLine();
        subline = (Subline) line.createSubline();
        transaction = (Transaction) subline.createTransaction();
        
        subline.add(transaction);
		line.add(subline);
		budget.add(line);
        
        budget.commit();
	}

	@After
	public void tearDown() throws Exception
	{
		System.out.println("Tear down");
		
		Helper.delete(transaction, "Transactions", WorkletContext.getInstance());
		Helper.delete(subline, "Sublines", WorkletContext.getInstance());
		Helper.delete(line, "Lines", WorkletContext.getInstance());
		Helper.delete(budget, "Budgets", WorkletContext.getInstance());
	}

	@SuppressWarnings("unchecked")
	@Test
	public void test()
	{
	 	 try
		 {
	 		 System.out.println("test");
            transaction.setName("This is our first transaction");
            budget.commit();
            
            BasicDBObject criteria = new BasicDBObject("entry.id", transaction.getId());
            String predicate = JSON.serialize(criteria);
			
			ArrayList<TransactionInterface> transactions = Helper.query("Transactions", predicate, WorkletContext.getInstance()); 

	        if(!( (Transaction) transactions.get(0)).getName().equals("This is our first transaction"))
	        {
	          	fail("Transaction name failed to update");
	        }
        }
        catch(Exception e)
        {
        	e.printStackTrace();
            fail("Update transaction name failed with exception: " + e);
        }
	}
}